package edu.scu.declaresys.web.action;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ModelDriven;

import edu.scu.declaresys.config.Configs;
import edu.scu.declaresys.config.IAttrName;
import edu.scu.declaresys.dao.util.Depth;
import edu.scu.declaresys.service.ServiceFactory;
import edu.scu.declaresys.service.intr.IAreaService;
import edu.scu.declaresys.service.intr.IUserService;
import edu.scu.declaresys.util.PageList;
import edu.scu.declaresys.util.Text;
import edu.scu.declaresys.vo.Area;
import edu.scu.declaresys.vo.User;
import edu.scu.declaresys.web.ABaseAction;
import edu.scu.declaresys.web.util.SessionUtil;

public class UserAction extends ABaseAction implements ModelDriven<User>
{
	private static final long	serialVersionUID	= -5031319689987021941L;
	
	private IUserService userService = ServiceFactory.createUserService();
	
	private IAreaService areaService = ServiceFactory.createAreaService();
	
	private User user = new User();
	
	private Integer page;
	
	private String oldPswd;
	
	private String newPswd;
	
	private String newPswdConfirm;
	
	
	//
	// 登入登出
	//
	public String login() throws Exception
	{
		if(user.getLoginName() == null || user.getPswd() == null)
		{
			return Action.INPUT;
		}
		//
		User vo = ServiceFactory.createUserValidateService().login(user.getLoginName(), user.getPswd());
		if(user != null)
		{
			request.getSession().setAttribute(User.T_TABLE, vo);
			return Action.SUCCESS;
		}
		//设置session过期时间
		request.getSession().setMaxInactiveInterval(Configs.SESSION_EXPIRE);
		return Action.INPUT;
	}
	
	public String logout() throws Exception
	{
		session.remove(User.T_TABLE);
		return Action.SUCCESS;
	}
	
	//
	// 用户管理
	//
	private String pswdConfirm;
	
	public String userRegister() throws Exception
	{
		/**
		 * check null or empty.
		 */
		if(user.getRole() == null
				|| user.getLoginName() == null
				|| user.getLoginName().trim().isEmpty()
				|| user.getPswd() == null
				|| user.getPswd().trim().isEmpty()
				|| user.getUnitName() == null
				|| user.getUnitName().trim().isEmpty()
				|| user.getAddress() == null
				|| user.getAddress().trim().isEmpty()
				|| user.getPhone() == null
				|| user.getPhone().trim().isEmpty()
				|| Text.isNullOrEmpty(pswdConfirm))
		{
			throw new Exception("未填字段未填写！");
		}
		if(!user.getPswd().equals(pswdConfirm))
		{
			throw new Exception("再次输入密码不同");
		}
		
		/**
		 * check logical.
		 */
		// check area exist or not. and get level.
		boolean isAreaExist = (areaService.findAreaById(user.getProvinceId(), Depth.ZERO) != null);
		int level = Area.LEVEL_PROVINCE;
		if(user.getCityId() != null)
		{
			isAreaExist = isAreaExist && (areaService.findAreaById(user.getCityId(), Depth.ZERO) != null);
			level = Area.LEVEL_CITY;
		}
		else
		{
			user.setCityId(Area.NULL_AREA_ID);
		}
		if(user.getCountyId() != null)
		{
			isAreaExist = isAreaExist && (areaService.findAreaById(user.getCountyId(), Depth.ZERO) != null);
			level = Area.LEVEL_COUNTY;
		}
		else
		{
			user.setCountyId(Area.NULL_AREA_ID);
		}
		if(isAreaExist == false)
		{
			throw new Exception("指定地区不存在！");
		}
		// check pswd
		if(userService.isPswdValid(user.getPswd()) == false)
		{
			throw new Exception("用户密码不合法。长度范围[6, 30]，至少为数字和字母的组合");
		}
		// Check role.
		int role = user.getRole();
		if(role != User.ROLE_PROJECT_AUDIT 
				&& role != User.ROLE_PROJECT_DECLARE
				&& role != User.ROLE_PROJECT_RECOMMEND
				&& role != User.ROLE_SYS_ADMIN)
		{
			throw new Exception("所选用户角色不存在");
		}
		if(user.getRole().equals(User.ROLE_PROJECT_DECLARE) == false)
		{
			/**
			 * 项目推荐人员，项目审批人员在同一地区只能有一个。
			 */
			if(userService.findUserList(user.getCityId(), user.getCountyId(), null, user.getRole(), null).isEmpty() == false)
			{
				throw new Exception("同一地区不能有多位推荐人员与审批人员");
			}
		}
		// Check auditor level.
		if(user.getRole().equals(User.ROLE_PROJECT_AUDIT) && user.getLevel().equals(Area.LEVEL_PROVINCE) == false)
		{
			throw new Exception("审批人员必须是省级用户");
		}
		
		/**
		 * set data.
		 */
		user.setProvinceId(Area.PROVINCE_ID);
		user.setLevel(level);
		if(user.getEmail() == null)
		{
			user.setEmail("");
		}
		request.setAttribute(IAttrName.USER_VO, userService.add(user));
		return Action.SUCCESS;
	}
	
	
	
	public String userAdminModifyBasicInfo() throws Exception
	{
		if(user.getId() == null)
		{
			throw new Exception("未指定用户！");
		}
		if(user.getAddress() == null
				|| user.getAddress().trim().isEmpty()
				|| user.getUnitName() == null
				|| user.getUnitName().trim().isEmpty()
				|| user.getPhone() == null
				|| user.getPhone().trim().isEmpty())
		{
			throw new Exception("未填字段未填写！");
		}
		userService.updateBasicInfo(user, user.getId());
		return Action.SUCCESS;
	}
	
	public String userShowUserForModify() throws Exception
	{
		if(user.getId() == null)
		{
			throw new Exception("未指定用户");
		}
		request.setAttribute(IAttrName.USER_VO, userService.findById(user.getId(), Depth.ONE));
		return Action.SUCCESS;
	}
	
	public String userDelete() throws Exception
	{
		if(user.getId() == null)
		{
			throw new Exception("未指定用户！");
		}
		userService.delete(user.getId());
		return Action.SUCCESS;
	}
	
	public String userList() throws Exception
	{
		if(page == null)
		{
			page = 1;
		}
		PageList<User> userLst = userService.findUserList(user.getCityId(), user.getCountyId(), user.getLoginName(), user.getRole(), page);
		request.setAttribute(IAttrName.USER_LIST, userLst);
		request.setAttribute(IAttrName.USER_LIST_SIZE, userLst.getDataAmt());
		return Action.SUCCESS;
	}
	
	public String userDetail() throws Exception
	{
		if(user.getId() == null)
		{
			throw new Exception("未指定用户！");
		}
		request.setAttribute(IAttrName.USER_VO, userService.findById(user.getId(), Depth.ONE));
		return Action.SUCCESS;
	}
	
	//
	// 修改与初始化密码
	//
	
	
	public String userInitPswd() throws Exception
	{
		if(user.getId() == null)
		{
			throw new Exception("未指定用户");
		}
		if(userService.isPswdValid(newPswd) == false)
		{
			throw new Exception("用户密码不合法。长度范围[6, 30]，至少为数字和字母的组合");
		}
		//修改密码
		userService.updatePswd(user.getId(), newPswd);
		return Action.SUCCESS;
	}

	//
	// 个人中心
	//
	public String personalInfo() throws Exception
	{
		request.setAttribute(IAttrName.USER_VO, userService.findById(SessionUtil.getCrtUserId(session), Depth.ONE));
		return Action.SUCCESS;
	}
	
	public String personalModifyPswd() throws Exception
	{
		// Check null.
		if(oldPswd == null 
				|| oldPswd.trim().isEmpty()
				|| newPswd == null
				|| newPswd.isEmpty())
		{
			throw new Exception("用户未指定或密码未填写！");
		}
		if(newPswd.equals(newPswdConfirm) == false)
		{
			throw new Exception("再次输入密码不一致");
		}
		user = SessionUtil.getCurrentUser(session);
		// Check user limits.
		if(user.getId().equals(SessionUtil.getCrtUserId(session)) == false)
		{
			throw new Exception("不能修改其他用户的密码！");
		}
				
		// Check oldPswd match or not.
		if(userService.isPswdMatch(user.getId(), oldPswd) == false)
		{
			throw new Exception("密码验证未通过");
		}
		if(userService.isPswdValid(newPswd) == false)
		{
			throw new Exception("用户密码不合法。长度范围[6, 30]，至少为数字和字母的组合");
		}
		//修改密码
		userService.updatePswd(user.getId(), newPswd);
		return Action.SUCCESS;
	}
	
	public String personalShowUserForModify() throws Exception
	{
		request.setAttribute(IAttrName.USER_VO, 
				userService.findById(SessionUtil.getCrtUserId(session), Depth.ONE));
		return Action.SUCCESS;
	}
	
	public String personalModifyInfo() throws Exception
	{
		User newUser = new User();
		newUser.setId(SessionUtil.getCrtUserId(session));
		newUser.setUnitName(user.getUnitName());
		newUser.setAddress(user.getAddress());
		newUser.setPhone(user.getPhone());
		newUser.setEmail(user.getEmail());
		//
		userService.updateBasicInfo(user, SessionUtil.getCrtUserId(session));
		//
		newUser = userService.findById(SessionUtil.getCrtUserId(session), Depth.ONE);
		request.setAttribute(IAttrName.USER_VO, newUser);
		return Action.SUCCESS;
	}
	
	//
	// Getter and Setter
	//
	@Override
	public User getModel()
	{
		return user;
	}
	
	public User getUser()
	{
		return user;
	}

	public void setUser(User user)
	{
		this.user = user;
	}

	

	public Integer getPage()
	{
		return page;
	}

	public void setPage(Integer page)
	{
		this.page = page;
	}

	public String getOldPswd()
	{
		return oldPswd;
	}

	public void setOldPswd(String oldPswd)
	{
		this.oldPswd = oldPswd;
	}

	public String getNewPswd()
	{
		return newPswd;
	}

	public void setNewPswd(String newPswd)
	{
		this.newPswd = newPswd;
	}

	public String getNewPswdConfirm()
	{
		return newPswdConfirm;
	}

	public void setNewPswdConfirm(String newPswdConfirm)
	{
		this.newPswdConfirm = newPswdConfirm;
	}

	public String getPswdConfirm()
	{
		return pswdConfirm;
	}

	public void setPswdConfirm(String pswdConfirm)
	{
		this.pswdConfirm = pswdConfirm;
	}
	
	
}
